package com.clstu.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Homework03Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口等待连接.....");
        Socket socket = serverSocket.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println("我收到了你发送的歌曲名:"+line+",正在向你发送....");
        String path = "D:\\CloudMusic\\"+line+".mp3";
        String reply = "找到了";
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        int readLen = 0;
        byte[] buf = new byte[1024];
        if(!new File(path).exists()) {
            path = "src\\mkbk.jpg";//假设默认传输一张图片(没找到)
            reply = "没找到";
        }
        bw.write(reply);
        bw.newLine();
        bw.flush();//结束标记

        FileInputStream fileInputStream = new FileInputStream(path);
        while ((readLen=fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,readLen);
        }
        socket.shutdownOutput();//结束标记

        fileInputStream.close();//关闭资源
        br.close();
        bw.close();
        socket.close();
        serverSocket.close();

    }
}
